import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../components/category_page.dart';
import './home_page.dart';

class EntryPage extends StatefulWidget {
  @override
  _EntryPageState createState() => _EntryPageState();
}

class _EntryPageState extends State<EntryPage> {
  // 底部导航项目
  final List<BottomNavigationBarItem> _routeList = [
    BottomNavigationBarItem(icon: Icon(Icons.list), title: Text('消息')),
    BottomNavigationBarItem(
        icon: Icon(Icons.contact_phone), title: Text('通讯录')),
    BottomNavigationBarItem(icon: Icon(Icons.shopping_cart), title: Text('发现')),
    BottomNavigationBarItem(icon: Icon(Icons.person), title: Text('我'))
  ];
  // 页面列表
  final List<Widget> _pageList = [
    HomePage(),
    CategoryPage(),
    HomePage(),
    CategoryPage()
  ];
  // 当前选中导航的index
  int _curIndex = 0;
  // 页面滑动控制器,必须使用构造函数初始化，不然方法无法使用
  PageController _pageController = PageController(initialPage: 0);

  // 根据 _curIndex 切换当前页面
  void _barItemTabHandle(index) {
    setState(() {
      _curIndex = index;
      _pageController.jumpToPage(_curIndex);
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil.getInstance()..init(context);
    return Scaffold(
      backgroundColor: Theme.of(context).primaryColor,
      body: PageView.builder(
        itemBuilder: (BuildContext context, int index) {
          return _pageList[index];
        },
        itemCount: _pageList.length,
        controller: _pageController,
        onPageChanged: (int index) {
          setState(() {
            _curIndex = index;
          });
        },
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        currentIndex: _curIndex,
        onTap: _barItemTabHandle,
        items: _routeList,
        backgroundColor: Color(0xffe7e7e7),
        fixedColor: Theme.of(context).primaryColorLight,
        unselectedItemColor: Colors.grey,
        selectedFontSize: 14,
        unselectedFontSize: 14,
      ),
    );
  }
}
